<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  getTravelNoteList,
  updateTravelNote,
  deleteTravelNote
} from '@/api/travelNote'
import {
  Star,
  Top,
  View,
  Delete,
  Refresh,
  TrendCharts
} from '@element-plus/icons-vue'

const router = useRouter()

// Tab 切换
const activeTab = ref('featured')

// 数据统计
const statistics = ref({
  featured: 0, // 精选数量
  top: 0, // 置顶数量
  popular: 0 // 热门数量
})

// 精选内容列表
const featuredList = ref([])
const featuredLoading = ref(false)
const featuredTotal = ref(0)
const featuredParams = ref({
  page: 1,
  pageSize: 10
})

// 置顶内容列表
const topList = ref([])
const topLoading = ref(false)
const topTotal = ref(0)
const topParams = ref({
  page: 1,
  pageSize: 10
})

// 热门内容列表
const popularList = ref([])
const popularLoading = ref(false)
const popularTotal = ref(0)
const popularParams = ref({
  page: 1,
  pageSize: 10
})

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 获取精选内容数量
    const featuredResult = await getTravelNoteList({
      is_featured: true,
      page: 1,
      pageSize: 1
    })
    statistics.value.featured = featuredResult.data?.total || 0

    // 获取置顶内容数量
    const topResult = await getTravelNoteList({
      is_top: true,
      page: 1,
      pageSize: 1
    })
    statistics.value.top = topResult.data?.total || 0

    // 获取热门内容数量
    const popularResult = await getTravelNoteList({
      status: 'approved',
      order_by: 'view_count',
      order: 'DESC',
      page: 1,
      pageSize: 1
    })
    statistics.value.popular = popularResult.data?.total || 0
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载精选内容
const loadFeaturedList = async () => {
  featuredLoading.value = true
  try {
    const result = await getTravelNoteList({
      is_featured: true,
      ...featuredParams.value
    })
    if (result.success) {
      featuredList.value = result.data.list || []
      featuredTotal.value = result.data.total || 0
    }
  } catch (error) {
    console.error('加载精选内容失败:', error)
  } finally {
    featuredLoading.value = false
  }
}

// 加载置顶内容
const loadTopList = async () => {
  topLoading.value = true
  try {
    const result = await getTravelNoteList({
      is_top: true,
      ...topParams.value
    })
    if (result.success) {
      topList.value = result.data.list || []
      topTotal.value = result.data.total || 0
    }
  } catch (error) {
    console.error('加载置顶内容失败:', error)
  } finally {
    topLoading.value = false
  }
}

// 加载热门内容
const loadPopularList = async () => {
  popularLoading.value = true
  try {
    const result = await getTravelNoteList({
      status: 'approved',
      order_by: 'view_count',
      order: 'DESC',
      ...popularParams.value
    })
    if (result.success) {
      popularList.value = result.data.list || []
      popularTotal.value = result.data.total || 0
    }
  } catch (error) {
    console.error('加载热门内容失败:', error)
  } finally {
    popularLoading.value = false
  }
}

// 切换精选状态
const toggleFeatured = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定${row.is_featured ? '取消' : '设置为'}精选吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await updateTravelNote(row.id, {
      is_featured: !row.is_featured
    })

    if (result.success) {
      ElMessage.success(`${row.is_featured ? '取消精选' : '设置精选'}成功`)
      loadFeaturedList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 切换置顶状态
const toggleTop = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定${row.is_top ? '取消' : '设置为'}置顶吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const result = await updateTravelNote(row.id, {
      is_top: !row.is_top
    })

    if (result.success) {
      ElMessage.success(`${row.is_top ? '取消置顶' : '设置置顶'}成功`)
      loadTopList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 设为精选
const setFeatured = async (row) => {
  try {
    const result = await updateTravelNote(row.id, {
      is_featured: true
    })

    if (result.success) {
      ElMessage.success('设置精选成功')
      loadPopularList()
      loadFeaturedList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 设为置顶
const setTop = async (row) => {
  try {
    const result = await updateTravelNote(row.id, {
      is_top: true
    })

    if (result.success) {
      ElMessage.success('设置置顶成功')
      loadPopularList()
      loadTopList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/travelNote`)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除这条内容吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const result = await deleteTravelNote(row.id)
    if (result.success) {
      ElMessage.success('删除成功')
      loadFeaturedList()
      loadTopList()
      loadPopularList()
      loadStatistics()
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 截取文本
const truncateText = (text, length = 30) => {
  if (!text) return '-'
  return text.length > length ? text.substring(0, length) + '...' : text
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// Tab 切换事件
const handleTabChange = (tab) => {
  if (tab === 'featured') {
    loadFeaturedList()
  } else if (tab === 'top') {
    loadTopList()
  } else if (tab === 'popular') {
    loadPopularList()
  }
}

// 分页变化
const handleFeaturedPageChange = (page) => {
  featuredParams.value.page = page
  loadFeaturedList()
}

const handleTopPageChange = (page) => {
  topParams.value.page = page
  loadTopList()
}

const handlePopularPageChange = (page) => {
  popularParams.value.page = page
  loadPopularList()
}

onMounted(() => {
  loadStatistics()
  loadFeaturedList()
})
</script>

<template>
  <div class="recommend-manage">
    <h2 class="page-title">⭐ 推荐设置</h2>

    <!-- 数据统计卡片 -->
    <div class="statistics-grid">
      <el-card class="stat-card featured" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><Star /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.featured }}</div>
            <div class="stat-label">精选内容</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card top" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><Top /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.top }}</div>
            <div class="stat-label">置顶内容</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card popular" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon :size="32"><TrendCharts /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ statistics.popular }}</div>
            <div class="stat-label">热门内容</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- Tab 内容区域 -->
    <el-card class="content-card">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 精选内容 -->
        <el-tab-pane label="⭐ 精选内容" name="featured">
          <div class="featured-section">
            <el-table
              :data="featuredList"
              v-loading="featuredLoading"
              border
              stripe
            >
              <el-table-column label="封面" width="80">
                <template #default="{ row }">
                  <el-image
                    v-if="row.cover_image"
                    :src="row.cover_image"
                    fit="cover"
                    style="width: 50px; height: 50px; border-radius: 4px"
                    :preview-src-list="[row.cover_image]"
                  />
                  <span v-else style="color: #999; font-size: 12px">无</span>
                </template>
              </el-table-column>

              <el-table-column prop="title" label="标题" min-width="200">
                <template #default="{ row }">
                  {{ truncateText(row.title, 25) }}
                </template>
              </el-table-column>

              <el-table-column prop="city" label="城市" width="100" />

              <el-table-column label="数据" width="150">
                <template #default="{ row }">
                  <div style="font-size: 12px">
                    <div>
                      👁️ {{ row.view_count || 0 }} | 👍
                      {{ row.like_count || 0 }}
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ row.status === 'approved' ? '已通过' : row.status }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="精选时间" width="140">
                <template #default="{ row }">
                  {{ formatDate(row.updated_at) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="warning"
                    size="small"
                    :icon="Star"
                    @click="toggleFeatured(row)"
                  >
                    取消精选
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="View"
                    @click="handleViewDetail(row)"
                  >
                    详情
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="handleDelete(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="featuredList.length === 0" class="empty-state">
              <el-empty description="暂无精选内容" />
            </div>

            <el-pagination
              v-if="featuredTotal > 0"
              class="pagination"
              :current-page="featuredParams.page"
              :page-size="featuredParams.pageSize"
              layout="total, prev, pager, next"
              :total="featuredTotal"
              @current-change="handleFeaturedPageChange"
              background
            />
          </div>
        </el-tab-pane>

        <!-- 置顶内容 -->
        <el-tab-pane label="📌 置顶内容" name="top">
          <div class="top-section">
            <el-table :data="topList" v-loading="topLoading" border stripe>
              <el-table-column label="封面" width="80">
                <template #default="{ row }">
                  <el-image
                    v-if="row.cover_image"
                    :src="row.cover_image"
                    fit="cover"
                    style="width: 50px; height: 50px; border-radius: 4px"
                    :preview-src-list="[row.cover_image]"
                  />
                  <span v-else style="color: #999; font-size: 12px">无</span>
                </template>
              </el-table-column>

              <el-table-column prop="title" label="标题" min-width="200">
                <template #default="{ row }">
                  {{ truncateText(row.title, 25) }}
                </template>
              </el-table-column>

              <el-table-column prop="city" label="城市" width="100" />

              <el-table-column label="数据" width="150">
                <template #default="{ row }">
                  <div style="font-size: 12px">
                    <div>
                      👁️ {{ row.view_count || 0 }} | 👍
                      {{ row.like_count || 0 }}
                    </div>
                  </div>
                </template>
              </el-table-column>

              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getStatusType(row.status)" size="small">
                    {{ row.status === 'approved' ? '已通过' : row.status }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="置顶时间" width="140">
                <template #default="{ row }">
                  {{ formatDate(row.updated_at) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                  <el-button
                    type="warning"
                    size="small"
                    :icon="Top"
                    @click="toggleTop(row)"
                  >
                    取消置顶
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="View"
                    @click="handleViewDetail(row)"
                  >
                    详情
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    @click="handleDelete(row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="topList.length === 0" class="empty-state">
              <el-empty description="暂无置顶内容" />
            </div>

            <el-pagination
              v-if="topTotal > 0"
              class="pagination"
              :current-page="topParams.page"
              :page-size="topParams.pageSize"
              layout="total, prev, pager, next"
              :total="topTotal"
              @current-change="handleTopPageChange"
              background
            />
          </div>
        </el-tab-pane>

        <!-- 热门内容 -->
        <el-tab-pane label="🔥 热门内容" name="popular">
          <div class="popular-section">
            <el-table
              :data="popularList"
              v-loading="popularLoading"
              border
              stripe
            >
              <el-table-column type="index" label="排名" width="70" />

              <el-table-column label="封面" width="80">
                <template #default="{ row }">
                  <el-image
                    v-if="row.cover_image"
                    :src="row.cover_image"
                    fit="cover"
                    style="width: 50px; height: 50px; border-radius: 4px"
                    :preview-src-list="[row.cover_image]"
                  />
                  <span v-else style="color: #999; font-size: 12px">无</span>
                </template>
              </el-table-column>

              <el-table-column prop="title" label="标题" min-width="200">
                <template #default="{ row }">
                  {{ truncateText(row.title, 25) }}
                </template>
              </el-table-column>

              <el-table-column prop="city" label="城市" width="100" />

              <el-table-column label="浏览量" width="100" sortable>
                <template #default="{ row }">
                  <span style="color: #e6a23c; font-weight: 500">
                    {{ row.view_count || 0 }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column label="点赞数" width="100" sortable>
                <template #default="{ row }">
                  <span style="color: #f56c6c; font-weight: 500">
                    {{ row.like_count || 0 }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column label="评论数" width="100" sortable>
                <template #default="{ row }">
                  <span style="color: #409eff; font-weight: 500">
                    {{ row.comment_count || 0 }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column label="发布时间" width="140">
                <template #default="{ row }">
                  {{ formatDate(row.published_at) }}
                </template>
              </el-table-column>

              <el-table-column label="操作" width="300" fixed="right">
                <template #default="{ row }">
                  <el-button
                    v-if="!row.is_featured"
                    type="warning"
                    size="small"
                    :icon="Star"
                    @click="setFeatured(row)"
                  >
                    设为精选
                  </el-button>
                  <el-button
                    v-if="!row.is_top"
                    type="success"
                    size="small"
                    :icon="Top"
                    @click="setTop(row)"
                  >
                    设为置顶
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="View"
                    @click="handleViewDetail(row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="popularList.length === 0" class="empty-state">
              <el-empty description="暂无热门内容" />
            </div>

            <el-pagination
              v-if="popularTotal > 0"
              class="pagination"
              :current-page="popularParams.page"
              :page-size="popularParams.pageSize"
              layout="total, prev, pager, next"
              :total="popularTotal"
              @current-change="handlePopularPageChange"
              background
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<style scoped>
.recommend-manage {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

/* 统计卡片网格 */
.statistics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
}

.stat-card.featured .stat-icon {
  background: #fdf6ec;
  color: #f59a23;
}

.stat-card.top .stat-icon {
  background: #f0f9ff;
  color: #409eff;
}

.stat-card.popular .stat-icon {
  background: #fef0f0;
  color: #f56c6c;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 内容卡片 */
.content-card {
  border-radius: 8px;
}

/* 各个部分 */
.featured-section,
.top-section,
.popular-section {
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

/* 分页 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .recommend-manage {
    padding: 10px;
  }

  .statistics-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .stat-value {
    font-size: 24px;
  }
}
</style>
